#! /usr/bin/env python
#coding=utf-8

import string
import sys
import os
import sqlite3
sys.path.append('../')
from tablebuilder import TableBuilder

class GroupTableBuilder(TableBuilder):
    def __init__(self, cursor):
        TableBuilder.__init__(self, cursor, "group_table")

    def getColumns(self):
        return ("name STRING PRIMARY KEY", "groupId INTEGER DEFAULT(-1)", "userNames STRING ")

    def getKeys(self):
        return ("name", "groupId", "userNames")

class PasswdTableBuilder(TableBuilder):
    def __init__(self, cursor):
        TableBuilder.__init__(self, cursor, "passwd_table")

    def getColumns(self):
        return ("name STRING PRIMARY KEY", "passwdId INTEGER DEFAULT(-1)", "groupId INTEGER DEFAULT(-1)")

    def getKeys(self):
        return ("name", "passwdId", "groupId")

class GroupFileParser():
    def __init__(self):
        self._group = {}

    def _handleGroupInfo(self, groupInfo):
        name = groupInfo[0].strip()
        userNames = name
        if len(groupInfo) > 3 and len(groupInfo[3]) > 0:
            userNames = groupInfo[3]
        oldGroup = self._group.get(name)
        if oldGroup:
            return
        group = {
            "name" : name,
            "groupId" : int(groupInfo[2], 10),
            "userNames" : userNames
        }
        self._group[name] = group

    def loadFile(self, fileName):
        #print(" loadFile %s" % fileName)
        with open(fileName, encoding='utf-8') as fp:
            line = fp.readline()
            while line :
                if line.startswith("#") or len(line) < 3:
                    line = fp.readline()
                    continue
                groupInfo = line.strip("\n").split(":")
                if len (groupInfo) < 3:
                    line = fp.readline()
                    continue
                self._handleGroupInfo(groupInfo)
                line = fp.readline()

    def dump(self):
        for group in self._group.values() :
            print(str(group))

    def _saveGroup(self, cursor):
        builder = GroupTableBuilder(cursor)
        builder.createTable()
        cnt = 0
        script = "BEGIN TRANSACTION;\n"
        for item in self._group.values():
            sqlcmd = builder.addObjectToDb(item, False, True)
            #print(sqlcmd)
            script = script + sqlcmd + ";\n"
            cnt = cnt + 1
        script = script + "COMMIT;\n"
        cursor = builder.getCursor()
        cursor.executescript(script)

    def save(self, path):
        print("save path %s" % path)
        conn = sqlite3.connect(path)
        cursor = conn.cursor()
        self._saveGroup(cursor)
        conn.commit()
        cursor.close()
        conn.close()

class PasswdFileParser():
    def __init__(self):
        self._passwd = {}

    def _handlePasswdInfo(self, passwdInfo):
        name = passwdInfo[0].strip()
        oldPasswd = self._passwd.get(name)
        if oldPasswd:
            return
        passwd = {
            "name" : name,
            "groupId" : int(passwdInfo[3], 10),
            "passwdId" : int(passwdInfo[2], 10)
        }
        self._passwd[name] = passwd

    def loadFile(self, fileName):
        print(" loadFile %s" % fileName)
        with open(fileName, encoding='utf-8') as fp:
            line = fp.readline()
            while line :
                if line.startswith("#") or len(line) < 3:
                    line = fp.readline()
                    continue
                passwdInfo = line.strip("\n").split(":")
                if len (passwdInfo) < 4:
                    line = fp.readline()
                    continue
                self._handlePasswdInfo(passwdInfo)
                line = fp.readline()

    def dump(self):
        for group in self._passwd.values() :
            print(str(group))

    def _savePasswd(self, cursor):
        builder = PasswdTableBuilder(cursor)
        builder.createTable()
        cnt = 0
        script = "BEGIN TRANSACTION;\n"
        for item in self._passwd.values():
            sqlcmd = builder.addObjectToDb(item, False, True)
            #print(sqlcmd)
            script = script + sqlcmd + ";\n"
            cnt = cnt + 1
        script = script + "COMMIT;\n"
        cursor = builder.getCursor()
        cursor.executescript(script)

    def save(self, path):
        print("save path %s" % path)
        conn = sqlite3.connect(path)
        cursor = conn.cursor()
        self._savePasswd(cursor)
        conn.commit()
        cursor.close()
        conn.close()

def _create_arg_parser():
    import argparse
    parser = argparse.ArgumentParser(description='Collect group information from system/etc/group dir.')
    parser.add_argument('-i', '--input',
                        help='input group files base directory example "out/rk3568/packages/phone/" ', required=True)

    parser.add_argument('-o', '--output',
                        help='output group information database directory', required=False)
    return parser

if __name__ == '__main__':
    args_parser = _create_arg_parser()
    options = args_parser.parse_args()

    parser = GroupFileParser()
    parser.loadFile(options.input + "/system/etc/group")
    #parser.dump()
    parser.save("group.db")

    passwd = PasswdFileParser()
    passwd.loadFile(options.input + "/system/etc/passwd")
    passwd.dump()
    passwd.save("passwd.db")

